import React from "react";
import { Dropdown, Menu, Table, TableProps } from "antd";
import { formatDate } from "utils";
import { ProjectType, UserType } from "types";
import { Link } from "react-router-dom";
import Pin from "components/pin";
import { useEditProject } from "server";
import { ButtonNoPadding } from "components/lib";
import { useProjectModal } from "hooks/useProjectModal";

interface ListType extends TableProps<ProjectType> {
  users: UserType[];
}

export const List: React.FC<ListType> = ({ users, ...others }) => {
  const { mutate } = useEditProject();
  const { edit } = useProjectModal();

  const pinProject = (id: number) => {
    return function (pin: boolean) {
      mutate({ id, pin });
    };
  };

  const editProjec = (id: number) => {
    return function () {
      edit(id);
    };
  };

  const operation = (id: number) => (
    <Dropdown
      overlay={
        <Menu>
          <Menu.Item key="edit" onClick={editProjec(id)}>
            编辑
          </Menu.Item>
          <Menu.Item key="delete">删除</Menu.Item>
        </Menu>
      }
    >
      <ButtonNoPadding type="link">...</ButtonNoPadding>
    </Dropdown>
  );

  return (
    <Table
      pagination={false}
      columns={[
        {
          title: <Pin checked={true} disabled={true} />,
          render: (_, { id, pin }) => {
            return <Pin checked={pin} onCheckedChange={pinProject(id)} />;
          },
        },
        {
          title: "名称",
          dataIndex: "name",
          sorter: (a, b) => a.name.localeCompare(b.name),
          render: (name, { id }) => <Link to={`${id}`}>{name}</Link>,
        },
        {
          title: "部门",
          dataIndex: "organization",
        },
        {
          title: "负责人",
          dataIndex: "id",
          render: (id) => users.find(({ id: _id }) => id === _id)?.name || "-",
        },
        {
          title: "创建时间",
          dataIndex: "created",
          render: formatDate,
        },
        {
          dataIndex: "id",
          title: "操作",
          render: operation,
        },
      ]}
      {...others}
    />
  );
};
